#!/bin/bash

if [ ! $1  ]; then
  echo "请输入操作: 'start | stop | restart'"
  exit
fi

if [ ! $2 ]; then
  echo "请输入服务名称....."
  exit
fi

appName=$2
appUrl=$appName'/*.jar'
appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`
heapSize='-Xms128m -Xmx256m'
appParam='-Djava.security.egd=file:/dev/./urandom'
agent='-javaagent:/root/skywalking-agent/skywalking-agent.jar=agent.service_name='$appName

allAppName=(chen-user chen-upms chen-auth)
allAppNameCount=${#allAppName[*]}

sourceJava(){
      echo "加载java环境..."
      source /etc/profile
      sleep 1
}

startApp(){
  if [ ! $appPid ]; then
      sourceJava

      echo "正在启动服务：$appName"
      nohup java $agent $heapSize $appParam -jar $appUrl > ./$appName/log.file 2>&1 &
      sleep 10

      count=0;
      while ((count <= 5)) ; do
          if [ ! $appPid ]; then
              sleep 2
              appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`
              ((count += 1))
          else
              break
          fi
      done

      if [ ! $appPid ]; then
          echo "$appName 服务：启动失败！"
      else
          echo "$appName 服务：启动成功，PID = $appPid"
      fi
  else
      echo "$appName 服务正在运行中，请不要重复启动！"
  fi
}

stopApp(){
  if [ $appPid ]; then
      echo "正在停止$appName 服务....."
      kill -2 $appPid

      count=0;
      while ((count <= 10)) ; do
          sleep 3
          appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`

          if [ $appPid ]; then
              ((count += 1))

              if [ $count == 11 ]; then
                  kill -9 $appPid
              fi
          else
              break
          fi
      done

      echo "$appName 服务：停止成功！"
  else
      echo "$appName 服务没有运行！请不要重复停止！"
  fi
}

# 启动所有服务
startAll(){
  count=0;
  while ((count < $allAppNameCount)) ; do
    sh deploy_cover.sh start ${allAppName[count]}
    ((count += 1))
  done
}

# 停止所有服务
stopAll(){
  count=0;
  while ((count < $allAppNameCount)) ; do
    sh deploy_cover.sh stop ${allAppName[count]}
    ((count += 1))
  done
}

mkdirAll(){
  count=0;
  while ((count < $allAppNameCount)) ; do
    mkdir -p ${allAppName[count]}
    echo "创建---${allAppName[count]}---文件夹"
    ((count += 1))
  done

  mkdir -p "tmp"
  echo "创建---tmp---文件夹"
}

if [ $appName == "all" ]; then
    if [ $1 == "start" ]; then
      startAll
    fi

    if [ $1 == "stop" ]; then
      stopAll
    fi

    if [ $1 == "mkdir" ]; then
      mkdirAll
    fi
else
    if [ $1 == "start" ]; then
      startApp
    fi

    if [ $1 == "stop" ]; then
      stopApp
    fi

    if [ $1 == "restart" ]; then
      sh deploy_cover.sh stop $appName
      sh deploy_cover.sh start $appName
    fi
fi

